package com.jinzhi.jzapi.common.controller;

import com.google.common.collect.Lists;
import com.jinzhi.jzapi.common.pojo.CerUtilsVo;
import com.jinzhi.jzapi.common.pojo.SchoolCerUtilsVO;
import com.jinzhi.jzapi.utils.CerSynthesisUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.TrainingCerVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.CertificateUtil;
import com.jinzhi.jzweb.utils.ValuesUtil;
import com.jinzhi.oss.service.OssService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;
import java.util.concurrent.*;

@Component
@Slf4j
public class SchoolApittController {
//    private static ExecutorService executor = new ThreadPoolExecutor(10, 10,
//            60L, TimeUnit.SECONDS,
//            new ArrayBlockingQueue(10));
    private final static   Executor executor = Executors.newFixedThreadPool(8);
    @Autowired
    private SchoolCertificatesService schoolCertificatesService;
    @Autowired
    private OssService ossService;
    @Autowired
    private CertificateManagementService certificateManagementService;


    public void testHandler(List<CertificateManagementDO> list){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    logicHandler(list);
                } catch (Exception e) {
                    log.warn("多线程同步稽查通话记录历史数据才处理异常，errMsg = {}", e);
                }
            }
        });
    }
    /**
     * List按指定长度分割
     * @param list the list to return consecutive sublists of （需要分隔的list）
     * @param size the desired size of each sublist (the last may be smaller) （分隔的长度）
     * @author songfayuan
     * @date 2019-07-07 21:37
     */
    public static <T> List<List<T>> partition(List<T> list, int size){
        return  Lists.partition(list, size); // 使用guava
    }

    /**
     * 处理数据逻辑
     * @throws Exception
     */
    private void logicHandler(List<CertificateManagementDO> list)  {
        /******添加任务******/
        List<Callable<List<CertificateManagementDO>>> tasks = new ArrayList<>();
            Callable<List<CertificateManagementDO>> qfe = new TestPllo(list);
            tasks.add(qfe);
        /******为避免太多任务的最终数据全部存在list导致内存溢出，故将任务再次拆分单独处理******/
     List <  List<CertificateManagementDO>> list1=ListUtils.partition(list, 8);
                            for(List <CertificateManagementDO> li:list1){
                            //利用线程池处理
                                executor.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        List<CertificateManagementDO> list2=li;
                                        List<CertificateManagementDO> certificateManagementDOS= new ArrayList<>();
                                        for(CertificateManagementDO li:list2){
                                            String  url = ossService.uploadFileOss2(li.getToUrl());
                                            li.setUrl(url);
                                            certificateManagementDOS.add(li);
                                        }
                                        certificateManagementService.insertBatch(certificateManagementDOS);

                                    }
                                });
                            }

    }

    //幼儿照护
    @Async
    public void yezhzssc(String unzipFileUrl,String UserId,File[] files,String certificateType,
                         String siteName,String examYear,String openingDate){
        List<CertificateManagementDO> certificateManagementDOS= new ArrayList<>();
         //files = new File(unzipFileUrl).listFiles(); //获取所有解压后的文件
        for (File f : files) {
            CertificateManagementDO certificateManagementDO =new CertificateManagementDO();
            String name = f.getName();
            certificateManagementDO.setName(name.substring(0, name.indexOf("("))); //截取学生姓名
            certificateManagementDO.setIdNumber(name.substring(name.indexOf("(")+1, name.indexOf(")"))); //截取身份证号码
            certificateManagementDO.setState(0); //默认证书状态为正常
            certificateManagementDO.setOperatorId(UserId); // 操作人id
            certificateManagementDO.setCreateTime(new Date()); //创建时间
            certificateManagementDO.setCertificateType(certificateType); //类型
            certificateManagementDO.setSiteName(siteName);//考核站点名称
            certificateManagementDO.setExamYear(examYear);//考试年份
           // certificateManagementDO.setOpeningDate(openingDate); //发证日期字段

            MultipartFile mFile = null;
            File vaf = new File(unzipFileUrl + name);
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(vaf);
                String fileName = vaf.getName();
                fileName = fileName.substring((fileName.lastIndexOf("/") + 1));
                try {
                    mFile =  new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //这里使用多线程来处理
                String  url = ossService.uploadFileOssName(mFile);
                certificateManagementDO.setUrl(url); //证书路径
                certificateManagementDOS.add(certificateManagementDO);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        certificateManagementService.insertBatch(certificateManagementDOS);
        try {
            deleteFile(new File(unzipFileUrl)); //删除解压后的证书文件
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
























    //幼儿照护
    @Async
    public void yezhzs(List<SchoolCerUtilsVO> schoolCerUtilsVOS, List<SchoolCertificatesDO> schoolCertificatesDOList){
        String s="幼儿照护";
        // 实现run方法
        for (int i = 0; i < schoolCerUtilsVOS.size(); i++) {
            //证书图片
            String cerImgUrl = null;
            String cerImgUrlNoSale = null;
            if (schoolCerUtilsVOS.get(i).getCertificatesType() == 1) {
                try {
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.yezhkhzdpb(0,schoolCerUtilsVOS.get(i).getBackgroundPath(),schoolCerUtilsVOS.get(i).getOrgName(),schoolCerUtilsVOS.get(i).getCode(),schoolCerUtilsVOS.get(i).getCerYear(),schoolCerUtilsVOS.get(i).getCerMath(),schoolCerUtilsVOS.get(i).getElectronicSeal(),s);
                    cerImgUrlNoSale = CerSynthesisUtil.yezhkhzdpb(1,schoolCerUtilsVOS.get(i).getBackgroundPath(),schoolCerUtilsVOS.get(i).getOrgName(),schoolCerUtilsVOS.get(i).getCode(),schoolCerUtilsVOS.get(i).getCerYear(),schoolCerUtilsVOS.get(i).getCerMath(),schoolCerUtilsVOS.get(i).getElectronicSeal(),s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (schoolCerUtilsVOS.get(i).getCertificatesType() == 2 || schoolCerUtilsVOS.get(i).getCertificatesType() == 3 || schoolCerUtilsVOS.get(i).getCertificatesType() == 4) {
                try {
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.yxsx_sfkhzd_yxkh(schoolCerUtilsVOS.get(i).getBackgroundPath(),schoolCerUtilsVOS.get(i).getOrgName(),schoolCerUtilsVOS.get(i).getCerYear(),schoolCerUtilsVOS.get(i).getCerMath(),s);
                    cerImgUrlNoSale = CerSynthesisUtil.yxsx_sfkhzd_yxkh(schoolCerUtilsVOS.get(i).getBackgroundPath(),schoolCerUtilsVOS.get(i).getOrgName(),schoolCerUtilsVOS.get(i).getCerYear(),schoolCerUtilsVOS.get(i).getCerMath(),s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //转换一下图片路径，将反斜杠替换掉
            String url = cerImgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
            String imgUrl1 = url.replace("\\", "/");

            schoolCertificatesDOList.get(i).setImgUrl(imgUrl1);//证书图片
            if (schoolCerUtilsVOS.get(i).getElectronicSealType() == 1) {
                //转换一下图片路径，将反斜杠替换掉
                String url1 = cerImgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                String imgUrl2 = url1.replace("\\", "/");
                schoolCertificatesDOList.get(i).setImgUrlNosale(imgUrl2);//不带电子公章的证书图片链接
            }

        }
        schoolCertificatesService.updateBatchById(schoolCertificatesDOList,schoolCertificatesDOList.size());
        System.out.println("修改成功------------------------------------------------------------------------------------");
    }

    //产后恢复
    @Async
    public void chhfzs(List<SchoolCerUtilsVO> schoolCerUtilsVOS, List<SchoolCertificatesDO> schoolCertificatesDOList){
        String s="产后恢复";
        // 实现run方法
        for (int i = 0; i < schoolCerUtilsVOS.size(); i++) {
            //证书图片
            String cerImgUrl = null;
            String cerImgUrlNoSale = null;
            if (schoolCerUtilsVOS.get(i).getCertificatesType() == 1) {
                try {
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.chhfkhzdpb(0,schoolCerUtilsVOS.get(i).getBackgroundPath(),schoolCerUtilsVOS.get(i).getOrgName(),schoolCerUtilsVOS.get(i).getCode(),schoolCerUtilsVOS.get(i).getCerYear(),schoolCerUtilsVOS.get(i).getCerMath(),schoolCerUtilsVOS.get(i).getElectronicSeal(),s);
                    cerImgUrlNoSale = CerSynthesisUtil.chhfkhzdpb(1,schoolCerUtilsVOS.get(i).getBackgroundPath(),schoolCerUtilsVOS.get(i).getOrgName(),schoolCerUtilsVOS.get(i).getCode(),schoolCerUtilsVOS.get(i).getCerYear(),schoolCerUtilsVOS.get(i).getCerMath(),schoolCerUtilsVOS.get(i).getElectronicSeal(),s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (schoolCerUtilsVOS.get(i).getCertificatesType() == 2 || schoolCerUtilsVOS.get(i).getCertificatesType() == 3 || schoolCerUtilsVOS.get(i).getCertificatesType() == 4) {
                try {
                    //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                    cerImgUrl = CerSynthesisUtil.yxsx_sfkhzd_yxkh(schoolCerUtilsVOS.get(i).getBackgroundPath(),schoolCerUtilsVOS.get(i).getOrgName(),schoolCerUtilsVOS.get(i).getCerYear(),schoolCerUtilsVOS.get(i).getCerMath(),s);
                    cerImgUrlNoSale = CerSynthesisUtil.yxsx_sfkhzd_yxkh(schoolCerUtilsVOS.get(i).getBackgroundPath(),schoolCerUtilsVOS.get(i).getOrgName(),schoolCerUtilsVOS.get(i).getCerYear(),schoolCerUtilsVOS.get(i).getCerMath(),s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //转换一下图片路径，将反斜杠替换掉
            String url = cerImgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
            String imgUrl1 = url.replace("\\", "/");

            schoolCertificatesDOList.get(i).setImgUrl(imgUrl1);//证书图片
            if (schoolCerUtilsVOS.get(i).getElectronicSealType() == 1) {
                //转换一下图片路径，将反斜杠替换掉
                String url1 = cerImgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                String imgUrl2 = url1.replace("\\", "/");
                schoolCertificatesDOList.get(i).setImgUrlNosale(imgUrl2);//不带电子公章的证书图片链接
            }

        }
        schoolCertificatesService.updateBatchById(schoolCertificatesDOList,schoolCertificatesDOList.size());
        System.out.println("修改成功------------------------------------------------------------------------------------");
    }
    private static void deleteFile(File file) throws IOException {
        File[] files = file.listFiles();
        if (files!=null){//如果包含文件进行删除操作
            for (int i = 0; i <files.length ; i++) {
                if (!files[i].getName().contains("jy")) {
                    if (files[i].isFile()) {
                        //删除子文件
                        files[i].delete();
                    } else if (files[i].isDirectory()) {
                        //通过递归的方法找到子目录的文件
                        deleteFile(files[i]);
                    }
                    files[i].delete();//删除子目录
                }
            }
        }
    }

    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        stringList.add("1");
        stringList.add("2");
        stringList.add("3");
        stringList.add("4");
        stringList.add("5");
        stringList.add("6");
        stringList.add("7");
        stringList.add("8");
        stringList.add("9");
        stringList.add("10");
        List<List<String>>  list=    ListUtils.partition(stringList, 3);
        System.out.println(list.size());
    }
}
